package com.examination.to.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.to.entity.Answer;
import com.examination.to.entity.Exam;
import com.examination.to.entity.Question;
import com.examination.to.mapper.AnswerMapper;
import com.examination.to.mapper.ExamMapper;
import com.examination.to.mapper.QuestionMapper;
import com.examination.to.service.QuestionService;
import com.examination.to.util.Result;
import com.examination.to.vo.QuestionVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * auther:FC
 * date:2021/5/11  21:18
 */

@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private ExamMapper examMapper;


    public Result addQustion(QuestionVo questionVo){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        Question question = new Question();
        List<Question> qus = questionMapper.selectList(new QueryWrapper<>());
        Integer currentquid = qus.size()+1;
        question.setId(currentquid);
        question.setQutype(questionVo.getQuestiontype());
        question.setQucontent(questionVo.getQuestioncontent());
        question.setCreateperson(questionVo.getCreateperson());
        question.setLevel(questionVo.getQuestionlevel());
        try {
            questionMapper.insert(question);
            StringBuffer mutiplechoice = new StringBuffer();
            if (questionVo.getQuestiontype() != 4){
                Answer answer = new Answer();
                answer.setId(currentquid);
                StringBuffer answers = new StringBuffer();
                for (int i = 0;i < questionVo.getAnswer().length;i++){
                    answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                    if (questionVo.getQuestiontype() == 2){
                        if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                            mutiplechoice.append(i).append(",");
                    }else {
                        if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                            answer.setTrueoption(i + "");
                    }
                }
                if (questionVo.getQuestiontype() == 2){
                    answer.setTrueoption(mutiplechoice.toString().substring(0,mutiplechoice.toString().length() - 1));
                }
                String handleAnswers = answers.toString();
                if (handleAnswers.length() != 0)
                    handleAnswers = handleAnswers.substring(0,handleAnswers.length() - 1);
                answer.setAlloptions(handleAnswers);
                answerMapper.insert(answer);
            }
            result.setCode(200);
            result.setMsg("添加试题成功");
            result.setDetail(question);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public Result addQuestionByBatch(List<QuestionVo> questionVos){
        Result result = new Result();
        result.setCode(-1);
        try {
            Integer eid;
            Exam examlast = examMapper.findlast();
            if (examlast == null){
                eid = 1;
            }else {
                eid = examlast.getId() + 1;
            }
            for (QuestionVo questionVo : questionVos) {
                Question last = questionMapper.findLast();
                Question question1 = new Question();
                question1.setCreateperson(questionVo.getCreateperson());
                question1.setScore(questionVo.getScore());
                if(last == null){
                    question1.setId(1);
                }else {
                    Integer lastid = last.getId();
                    question1.setId(++lastid);
                }
                question1.setLevel(questionVo.getQuestionlevel());
                question1.setQucontent(questionVo.getQuestioncontent());
                question1.setQutype(questionVo.getQuestiontype());
                question1.setExamid(eid);
                questionMapper.insert(question1);
                StringBuffer mutiplechoice = new StringBuffer();
                if (questionVo.getQuestiontype() != 4 & questionVo.getQuestiontype() < 4){
                    Answer answer = new Answer();
                    answer.setExamid(eid);
                    Question last2 = questionMapper.findLast();
                    Integer lastid = last2.getId();
                    answer.setQuestionid(lastid);
                    StringBuffer answers = new StringBuffer();
                    for (int i = 0;i<questionVo.getAnswer().length;i++){
                        answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                        if (questionVo.getQuestiontype() == 2){
                            if (questionVo.getAnswer()[i].getIstrue().equals("True")){
                                mutiplechoice.append(i).append(",");
                            }
                        }else {
                            if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                answer.setTrueoption(i + "");
                        }
                    }
                    if (questionVo.getQuestiontype() == 3){
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i=0;i<questionVo.getAnswer().length;i++){
                            if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                if (i == questionVo.getAnswer().length - 1)
                                    stringBuffer.append("True");
                                else
                                    stringBuffer.append("True").append(",");
                            else
                                if (i == questionVo.getAnswer().length - 1)
                                    stringBuffer.append("false");
                                else
                                    stringBuffer.append("false").append(",");

                        }
                        answer.setJudge(stringBuffer.substring(0,stringBuffer.length()));
                    }
                    if (questionVo.getQuestiontype() == 2){
                        answer.setTrueoption(mutiplechoice.toString());
                    }
                    String handleAnswers = answers.toString();
                    if (handleAnswers.length() != 0)
                        handleAnswers = handleAnswers.substring(0,handleAnswers.length() - 1);
                    answer.setAlloptions(handleAnswers);
                    answerMapper.insert(answer);
                }else if (questionVo.getQuestiontype() == 4){
                    Answer answer = new Answer();
                    Question last1 = questionMapper.findLast();
                    Integer lastid = last1.getId();
                    answer.setQuestionid(lastid);
                    answer.setExamid(eid);
                    answer.setText(questionVo.getAnswer()[0].getAnswer());
                    answer.setAnalysis(questionVo.getAnalysis());
//                    answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                    answerMapper.insert(answer);
                }else if (questionVo.getQuestiontype() == 5){
                    question1.setScore(null);
                    question1.setStuinfo(questionVo.getStuinfo());
                    questionMapper.updateById1(question1);
                }else if (questionVo.getQuestiontype() == 6){
//                    Answer answer = new Answer();
//                    Question last1 = questionMapper.findLast();
//                    Integer lastid = last1.getId();
//                    answer.setQuestionid(lastid);
//                    answer.setExamid(eid);
//                    answer.setText(questionVo.getAnswer()[0].getText());
//                    answerMapper.insert(answer);
                    continue;
                }
            }
            result.setCode(200);
            result.setMsg("批量添加成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public Result deleteQustion(Question question){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try {
            QueryWrapper<Question> wrapper = new QueryWrapper<>();
            wrapper.eq("examid",question.getExamid());
            List<Question> questions = questionMapper.selectList(wrapper);
            int index = question.getId();
            Question temp = questions.remove(index-1);
            wrapper.eq("id",temp.getId());
            questionMapper.delete(wrapper);
            QueryWrapper<Answer> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id",temp.getId());
            wrapper1.eq("examid",question.getExamid());
            answerMapper.delete(wrapper1);
            result.setCode(200);
            result.setMsg("删除试题成功");
            result.setDetail(question);

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public Result updateQuestionByBatch(List<QuestionVo> questionVos){
        Result result = new Result();
        result.setCode(200);
        result.setDetail(null);
        try{
            for (QuestionVo questionVo : questionVos) {
                QueryWrapper<Question> wrapper = new QueryWrapper<>();
                wrapper.eq("examid",questionVo.getExamid());
                List<Question> questions = questionMapper.selectList(wrapper);
                Question question1 = new Question();
                Question index = questions.get(questionVo.getId()-1);
                question1.setCreateperson(questionVo.getCreateperson());
                question1.setQucontent(questionVo.getQuestioncontent());
                question1.setLevel(questionVo.getQuestionlevel());
                question1.setQutype(questionVo.getQuestiontype());
                question1.setExamid(questionVo.getExamid());
                question1.setId(index.getId());
                questionMapper.updateById1(question1);
                StringBuffer mutiplechoice = new StringBuffer();
                if (questionVo.getQuestiontype() != 4) {
                    Answer answer = new Answer();
                    QueryWrapper<Answer> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("examid",questionVo.getExamid());
                    List<Answer> answerss = answerMapper.selectList(wrapper1);
                    Answer index1 = answerss.get(questionVo.getId()-1);
                    answer.setId(index1.getId());
                    StringBuffer answers = new StringBuffer();
                    for (int i = 0; i < questionVo.getAnswer().length; i++) {
                        answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                        if (questionVo.getQuestiontype() == 2) {
                            if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                mutiplechoice.append(i).append(",");
                        } else {
                            if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                answer.setTrueoption(i + "");
                        }
                    }
                    if (questionVo.getQuestiontype() == 2) {
                        answer.setTrueoption(mutiplechoice.toString().substring(0, mutiplechoice.toString().length() - 1));
                    }
                    String handleAnswers = answers.toString();
                    if (handleAnswers.length() != 0)
                        handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);
                    answer.setAlloptions(handleAnswers);
                    answerMapper.updateById2(answer);
                }
            }
            result.setCode(200);
            result.setMsg("批量修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public List<QuestionVo> showQuestions(Exam exam) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("examid", exam.getId());
        List<Question> qus = questionMapper.selectList(queryWrapper);
        if (qus == null) {
            return null;
        }
        List<QuestionVo> questionVos = new ArrayList<>();
        for (Question question : qus) {
            if (question.getQutype() == 1) {
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setScore(question.getScore());
                questionVo.setQuestionid(question.getId());
                Answer answer = answerMapper.findByQuestionId(question.getId());
                if (answer == null) {
                    return null;
                } else {
                    //把类型为string的所有选项按逗号隔开转化为string数组
                    String[] answers = answer.getAlloptions().split(",");
                    //把类型为string的正确选项索引按逗号隔开转化为string数组
                    String[] trueoption = answer.getTrueoption().split(",");
                    //将正确选项索引的string数组转化为类型为Integer数组
                    Integer[] trueoption1 = (Integer[]) ConvertUtils.convert(trueoption, Integer.class);
                    //该list添加从数据库获得的Answer
                    List<QuestionVo.Answer> list = new ArrayList<>();
                    for (int i = 0; i < answers.length; i++) {
                        //new一个QuestionVo内部类Answer用来过渡到实体类Answer
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setAnswer(answers[i]);
                        for (int j=0;j<trueoption1.length;j++){
                            if (trueoption1[j] == i) {
                                answer1.setIstrue("True");
                                break;
                            } else
                                answer1.setIstrue("False");
                        }
                        list.add(answer1);
                    }
                    QuestionVo.Answer[] answers1 = list.toArray(new QuestionVo.Answer[list.size()]);
                    questionVo.setAnswer(answers1);
                    questionVo.setQuestiontype(question.getQutype());
                    questionVo.setCreateperson(question.getCreateperson());
                    questionVo.setQuestioncontent(question.getQucontent());
                    questionVos.add(questionVo);
                }
            } else if (question.getQutype() == 2) {
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setScore(question.getScore());
                questionVo.setQuestionid(question.getId());
                Answer answer = answerMapper.findByQuestionId(question.getId());
                if (answer == null) {
                    return null;
                } else {
                    //把类型为string的所有选项按逗号隔开转化为string数组
                    String[] answers = answer.getAlloptions().split(",");
                    //把类型为string的正确选项索引按逗号隔开转化为string数组
                    String[] trueoption = answer.getTrueoption().split(",");
                    //将正确选项索引的string数组转化为类型为Integer数组
                    Integer[] trueoption1 = (Integer[]) ConvertUtils.convert(trueoption, Integer.class);
                    //该list添加从数据库获得的Answer
                    List<QuestionVo.Answer> list = new ArrayList<>();

                    for (int i = 0; i < answers.length; i++) {
                        //new一个QuestionVo内部类Answer用来过渡到实体类Answer
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setAnswer(answers[i]);
                        for (int j=0;j<trueoption1.length;j++){
                            if (trueoption1[j] == i) {
                                answer1.setIstrue("True");
                                break;
                            } else
                                answer1.setIstrue("False");
                        }
                        list.add(answer1);
                    }
                    QuestionVo.Answer[] answers1 = list.toArray(new QuestionVo.Answer[list.size()]);
                    questionVo.setAnswer(answers1);
                    questionVo.setQuestiontype(question.getQutype());
                    questionVo.setCreateperson(question.getCreateperson());
                    questionVo.setQuestioncontent(question.getQucontent());
                    questionVos.add(questionVo);
                }
            } else if (question.getQutype() == 3) {
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setQuestionid(question.getId());
                questionVo.setScore(question.getScore());
                Answer answer = answerMapper.findByQuestionId(question.getId());
                if (answer == null) {
                    return null;
                } else {
                    //把类型为string的所有选项按逗号隔开转化为string数组
                    String[] answers = answer.getAlloptions().split(",");
                    //该list添加从数据库获得的Answer
                    List<QuestionVo.Answer> list = new ArrayList<>();
                    //将string类型的judge按逗号隔开装成string数组
                    String[] judges = answer.getJudge().split(",");
                    for (int i=0;i<judges.length;i++){
                        //new一个QuestionVo内部类Answer用来过渡到实体类Answer
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setAnswer(answers[i]);
                        if (judges[i].equals("True"))
                            answer1.setIstrue("True");
                        else
                            answer1.setIstrue("False");
                        list.add(answer1);
                    }
                    QuestionVo.Answer[] answers1 = list.toArray(new QuestionVo.Answer[list.size()]);
                    questionVo.setAnswer(answers1);
                    questionVo.setQuestiontype(question.getQutype());
                    questionVo.setCreateperson(question.getCreateperson());
                    questionVo.setQuestioncontent(question.getQucontent());
                    questionVos.add(questionVo);
                }

            }else if (question.getQutype() == 4){
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setQuestionid(question.getId());
                questionVo.setScore(question.getScore());
                Answer answer = answerMapper.findByQuestionId(question.getId());
                if (answer == null) {
                    return null;
                } else {
                    QuestionVo.Answer answer1 = new QuestionVo.Answer();
                    answer1.setText(answer.getText());
                    answer1.setAnswer(answer.getTrueoption());
                    //该list添加从数据库获得的Answer
                    List<QuestionVo.Answer> list = new ArrayList<>();
                    list.add(answer1);
                    QuestionVo.Answer[] answers1 = list.toArray(new QuestionVo.Answer[list.size()]);
                    questionVo.setAnswer(answers1);
                    questionVo.setQuestiontype(question.getQutype());
                    questionVo.setCreateperson(question.getCreateperson());
                    questionVo.setQuestioncontent(question.getQucontent());
                    questionVos.add(questionVo);
                }
            }else if (question.getQutype() == 5){
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setScore(question.getScore());
                questionVo.setQuestionid(question.getId());
                questionVo.setQuestiontype(question.getQutype());
                questionVo.setCreateperson(question.getCreateperson());
                questionVo.setQuestioncontent(question.getQucontent());
                questionVo.setStuinfo(question.getStuinfo());
                questionVos.add(questionVo);
            }else if (question.getQutype() == 6){
                QuestionVo questionVo = new QuestionVo();
                questionVo.setExamid(question.getExamid());
                questionVo.setId(question.getId());
                questionVo.setScore(question.getScore());
                questionVo.setQuestionid(question.getId());
                questionVo.setQuestiontype(question.getQutype());
                questionVo.setCreateperson(question.getCreateperson());
                questionVo.setQuestioncontent(question.getQucontent());
                questionVos.add(questionVo);
            }
        }
        return questionVos;
    }
}
